﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Odyssey.Controls.Models;

namespace Odyssey.Controls
{
    public class TimePicker : Control
    {
        public TimePicker()
            : base()
        {
            base.DefaultStyleKey = typeof(TimePicker);
            model = new TimePickerModel();
            Context = model;
            Time = model.Time;
            model.TimeChanged += (s, e) => Time = model.Time;
        }       

        private TimePickerModel model;




        public object Context
        {
            get { return (object)GetValue(ContextProperty); }
            private set { SetValue(ContextProperty, value); }
        }

        public static readonly DependencyProperty ContextProperty =
            DependencyProperty.Register("Context", typeof(object), typeof(TimePicker), new PropertyMetadata(null));

        


        public DateTime Time
        {
            get { return (DateTime)GetValue(TimeProperty); }
            set { SetValue(TimeProperty, value); }
        }

        public static readonly DependencyProperty TimeProperty =
            DependencyProperty.Register("Time", typeof(DateTime), typeof(TimePicker), new PropertyMetadata(DateTime.Now, OnTimeChanged));


        private static void OnTimeChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            (o as TimePicker).OnTimeChanged((DateTime)args.OldValue, (DateTime)args.NewValue);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            if (VisualTreeHelper.GetChildrenCount(this) > 0)
            {
       //         (VisualTreeHelper.GetChild(this, 0) as FrameworkElement).DataContext = model;
            }
        }

        protected virtual void OnTimeChanged(DateTime oldValue, DateTime newValue)
        {
            model.Time = newValue;
            var eh = TimeChanged;
            if (eh != null) eh(this, EventArgs.Empty);
        }

        public event EventHandler TimeChanged;
    }
}
